package logic

import (
	"log"
	"ms_sg_game/constant"
	"ms_sg_game/db"
	"ms_sg_game/server/common"
	"ms_sg_game/server/models"
	"ms_sg_game/server/web/model"
	"ms_sg_game/utils"
	"time"
)

var DefaultAccountLogin = &AccountLogic{}

type AccountLogic struct {
}

/*
*
具体的注册的逻辑
*/
func (al *AccountLogic) Register(rq *model.RegisterReq) error {
	username := rq.Username
	var user = &models.User{}
	ok, err := db.Engine.Table(user).Where("username=?", username).Get(user)
	if err != nil {
		//数据库错误
		log.Println("数据库查询错误", err)
		return common.New(constant.DBError, "数据库查询错误")
	}
	if ok {
		log.Println("当前用户已经注册了:", username)
		return common.New(constant.DBError, "当前用户已经注册")
	}
	//进行注册
	user.Hardware = rq.Hardware
	user.Username = username
	user.Ctime = time.Now()
	user.Mtime = time.Now()
	user.Passcode = utils.RandSeq(6)
	user.Passwd = utils.Password(rq.Password, user.Passcode)
	_, err = db.Engine.Table(user).Insert(user)
	if err != nil {
		log.Println("用户注册插入数据失败", username)
		return common.New(constant.DBError, "用户注册插入数据失败")
	}
	return nil
}
